<?php

namespace System\Core;

class Config
{
    private static $config = [];

    public static function loadEnv($file)
    {
        if (!file_exists($file)) return;

        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        foreach ($lines as $line) {
            if (strpos(trim($line), '#') === 0) continue;

            list($name, $value) = explode('=', $line, 2);
            $name = trim($name);
            $value = trim($value);

            // 处理引号包裹的值
            if (preg_match('/^([\'"])(.*)\1$/', $value, $matches)) {
                $value = $matches[2];
            }

            putenv("$name=$value");
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }

    public static function get($key, $default = null)
    {
        // 先尝试从环境变量获取
        $value = getenv($key);
        if ($value !== false) return $value;

        // 然后尝试从配置数组获取
        return self::$config[$key] ?? $default;
    }

    public static function set($key, $value)
    {
        self::$config[$key] = $value;
    }

    public static function load()
    {
        $dir = dir(BASE_PATH . '/config');
        while ($row = $dir->read()) {
            if (strpos($row, '.php')!==false) {
                $file = $row;
                $configFile = BASE_PATH . '/config/' . $file;
                if (file_exists($configFile)) {
                    self::$config = array_merge(self::$config, require $configFile);
                }
            }
        }
    }
}
